﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class Forum_Forum : System.Web.UI.Page
{
    public int ForumID
    {
        get
        {
            int id = -1;
            if (Request.QueryString["ForumID"] != null)
                Int32.TryParse(Request.QueryString["ForumID"], out id);
            return id;
        }
    }

    public int ThreadID
    {
        get
        {
            int id = -1;
            if (Request.QueryString["ThreadID"] != null)
                Int32.TryParse(Request.QueryString["ThreadID"], out id);
            return id;
        }
    }

    public string CourseID
    {
        get
        {
            if (Request.QueryString["CourseID"] != null)
                return Request.QueryString["CourseID"];
            return "-1";
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (ForumID != -1)
        {
            lblForumTitle.Text = new LMSData.Forum(ForumID).ForumName;
            lblforumText.Text = new LMSData.Forum(ForumID).ForumText.Replace("$IMS-CC-FILEBASE$..", Utility.GetSiteRoot() + "/Course/Courses/" + CourseID);
        }

        LoadThreads();

        if (ThreadID != -1)
        {
            lblForumTitle.Text += " - " + new LMSData.Thread(ThreadID).ThreadName;
            LoadMessages();
        }
        else
            upnlMessages.Visible = false;
    }

    private void LoadThreads()
    {
        LMSData.ThreadCollection tc = new LMSData.ThreadCollection();
        SubSonic.Query qry = new SubSonic.Query(LMSData.Thread.Schema).WHERE(LMSData.Thread.Columns.ForumID, ForumID);
        tc.LoadAndCloseReader(qry.ExecuteReader());

        List<ThreadAxis> ThreadList = MakeThreadList(tc);

        ThreadList = MakeThreadList(tc);

        RepThreads.Controls.Clear();
        foreach (ThreadAxis ta in ThreadList)
        {
            DisplayThreadList(ta);
        }
    }

    private void DisplayThreadList(ThreadAxis ta)
    {
        HyperLink hl = new HyperLink();
        hl.Font.Underline = false;
        hl.Font.Size = 10;
        if (ta.Self.ThreadID == ThreadID)
        {
            if (((int)ta.Self.Depth) == 0)
                hl.Text = "<br><b>" + AddTabs((int)ta.Self.Depth) + ta.Self.ThreadName + " - " + ((DateTime)(ta.Self.CreatedOn)).ToLongDateString() + " " + ((DateTime)(ta.Self.CreatedOn)).ToLongTimeString() + "</b><br><br>";
            else
                hl.Text = "<b>" + AddTabs((int)ta.Self.Depth) + ta.Self.ThreadName + " - " + ((DateTime)(ta.Self.CreatedOn)).ToLongDateString() + " " + ((DateTime)(ta.Self.CreatedOn)).ToLongTimeString() + "</b><br><br>";
        }
        else
        {
            if (((int)ta.Self.Depth) == 0)
                hl.Text = "<br>" + AddTabs((int)ta.Self.Depth) + ta.Self.ThreadName + " - " + ((DateTime)(ta.Self.CreatedOn)).ToLongDateString() + " " + ((DateTime)(ta.Self.CreatedOn)).ToLongTimeString() + "<br><br>";
            else
                hl.Text = AddTabs((int)ta.Self.Depth) + ta.Self.ThreadName + " - " + ((DateTime)(ta.Self.CreatedOn)).ToLongDateString() + " " + ((DateTime)(ta.Self.CreatedOn)).ToLongTimeString() + "<br><br>";
        }
        hl.NavigateUrl = "~/Course/Forum.aspx?ForumID=" + ForumID.ToString() + "&ThreadID=" + ta.Self.ThreadID.ToString();
        RepThreads.Controls.Add(hl);
        foreach (ThreadAxis child in ta.Children)
            DisplayThreadList(child);
    }

    private List<ThreadAxis> MakeThreadList(LMSData.ThreadCollection tc)
    {
        List<ThreadAxis> ThreadList = new List<ThreadAxis>();
        List<ThreadAxis> SubThreadList = new List<ThreadAxis>();
        bool FirstParent = true;
        LMSData.Thread tempThread = new LMSData.Thread();

        if (ThreadID != -1)
            tempThread = new LMSData.Thread(ThreadID);

        if (ThreadID == -1 || tempThread.ParentThread == null)
        {
            foreach (LMSData.Thread thrd in tc)
            {
                ThreadAxis ta = new ThreadAxis();
                if (thrd.ParentID == null)
                {
                    ta.Self = thrd;
                    ta.Children = AddChildren(thrd.ThreadID, tc);
                    ThreadList.Add(ta);
                }
            }
        }
        else
        {
            tempThread = new LMSData.Thread(ThreadID);
            foreach (LMSData.Thread thrd in tc)
            {
                ThreadAxis ta = new ThreadAxis();
                if (thrd.ParentID == tempThread.ParentID)
                {
                    ta.Self = thrd;
                    ta.Children = AddChildren(thrd.ThreadID, tc);
                    SubThreadList.Add(ta);
                }
            }

            ThreadAxis pta = null;

            while (tempThread.ParentID != null)
            {
                ThreadAxis ta = new ThreadAxis();
                List<ThreadAxis> ITL;
                tempThread = tempThread.ParentThread;
                ta.Self = tempThread;
                if (FirstParent)
                {
                    ta.Children = SubThreadList;
                    FirstParent = false;
                }
                else
                {
                    ITL = new List<ThreadAxis>();
                    ITL.Add(pta);
                    ta.Children = ITL;
                }
                pta = ta;
            }
            ThreadList.Add(pta);
        }

        return ThreadList;
    }

    private List<ThreadAxis> AddChildren(int tID, LMSData.ThreadCollection tc)
    {
        List<ThreadAxis> Children = new List<ThreadAxis>();
        foreach (LMSData.Thread thrd in tc)
        {
            ThreadAxis ta = new ThreadAxis();
            if (thrd.ParentID == tID)
            {
                ta.Self = thrd;
                ta.Children = AddChildren(thrd.ThreadID, tc);
                Children.Add(ta);
            }
        }
        return Children;
    }

    public class ThreadAxis
    {
        public LMSData.Thread Self;
        public LMSData.Thread Parent;
        public List<ThreadAxis> Children;
    }

    private string AddTabs(int Tabs)
    {
        string ts = "";
        int i = 0;
        while (i < Tabs)
        {
            ts += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
            i++;
        }
        return ts;
    }

    protected void AddThread(object sender, EventArgs e)
    {
        int UserID = 0;
        try
        {
            UserID = Convert.ToInt32(Membership.GetUser().ProviderUserKey);
        }
        catch
        {
            ErrorMessage.Text = "<br>Session Timed Out: Please Login Again";
            return;
        }

        LMSData.Thread thrd = new LMSData.Thread();
        if (ForumID != -1)
        {
            thrd.ThreadName = NewThread.Text;
            thrd.ForumID = ForumID;
            if (ThreadID != -1)
            {
                thrd.ParentID = ThreadID;
                thrd.Depth = (int)new LMSData.Thread(ThreadID).Depth + 1;
            }
            else
                thrd.Depth = 0;
            thrd.UserID = UserID;
            thrd.IsDeleted = false;
            thrd.Save();
        }
        LoadThreads();
    }

    private void LoadMessages()
    {
        RepMessages.Controls.Clear();
        LMSData.MessageCollection mcl = new LMSData.MessageCollection();
        SubSonic.Query qry = new SubSonic.Query(LMSData.Message.Schema).WHERE(LMSData.Message.Columns.ThreadID, ThreadID);
        mcl.LoadAndCloseReader(qry.ExecuteReader());

        foreach (LMSData.Message msg in mcl)
        {
            int UserID = 0;
            try
            {
                UserID = Convert.ToInt32(Membership.GetUser().ProviderUserKey);
            }
            catch
            {
                ErrorMessage.Text = "<br>Session Timed Out: Please Login Again";
                return;
            }

            LMSData.Message ParentMessage = null;
            LMSData.MessageCollection posts = new LMSData.MessageCollection();
            qry = new SubSonic.Query(LMSData.Message.Schema).WHERE(LMSData.Message.Columns.UserID);
            posts.LoadAndCloseReader(qry.ExecuteReader());

            LMSData.User usr = new LMSData.User(msg.UserID);
            Course_UserControls_ForumMessage ForumMessage = (Course_UserControls_ForumMessage)LoadControl("~/Course/UserControls/ForumMessage.ascx");
            ForumMessage.UserName = usr.Username;
            ForumMessage.Title = msg.MessageTitle;
            ForumMessage.Message = msg.MessageX;
            ForumMessage.MessageDate = ((DateTime)msg.CreatedOn).ToLongDateString() + " - " + ((DateTime)msg.CreatedOn).ToLongTimeString();
            ForumMessage.Joined = ((DateTime)usr.CreatedOn).ToShortDateString();
            ForumMessage.Posts = posts.Count.ToString();
            ForumMessage.ForumID = ForumID;
            ForumMessage.ThreadID = ThreadID;
            ForumMessage.ParentID = msg.MessageID;
            
            if (msg.ParentID != null && msg.ParentID != -1)
            {
                ParentMessage = new LMSData.Message((int)msg.ParentID);
                ForumMessage.Quote = "<b>" + new LMSData.User(msg.UserID).Username + "</b> says:<br><br>" + ParentMessage.MessageX;
            }

            ForumMessage.LM = new Course_UserControls_ForumMessage.LoadMessages(LoadMessages);

            if (msg.UserID == UserID || Roles.IsUserInRole(new LMSData.User(UserID).Username, "Admin"))
                ForumMessage.DeleteID = msg.MessageID;

            if (msg.IsDeleted != null)
            {
                if ((bool)msg.IsDeleted)
                    ForumMessage.IsDeleted = true;
            }

            RepMessages.Controls.Add(ForumMessage);
        }
    }

    protected void PostMessage(object sender, EventArgs e)
    {
        int UserID = 0;
        try
        {
            UserID = Convert.ToInt32(Membership.GetUser().ProviderUserKey);
        }
        catch
        {
            ErrorMessage.Text = "<br>Session Timed Out: Please Login Again";
            return;
        }
        LMSData.Message msg = new LMSData.Message();
        if (ThreadID != -1)
        {
            msg.MessageTitle = NewTitle.Text;
            msg.UserID = Convert.ToInt32(Membership.GetUser().ProviderUserKey);
            msg.MessageX = NewMessage.Text;
            msg.ThreadID = ThreadID;
            msg.Sequence = 1;
            msg.ParentID = -1;
            msg.IsDeleted = false;
            msg.Save();
        }

        LoadMessages();
    }
}
